package com.fy.service.impl;

import com.aliyun.oss.model.BucketStat;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.common.constants.Constants;
import com.fy.common.constants.MessageConstant;

import com.fy.ex.ConditionException;
import com.fy.mapper.*;
import com.fy.pojo.entity.Expansion;
import com.fy.pojo.entity.Position;
import com.fy.pojo.entity.SysFunction;
import com.fy.pojo.entity.SysTools;
import com.fy.pojo.vo.other.DurationTimeVO;
import com.fy.pojo.vo.user.LoginUserVO;
import com.fy.pojo.vo.other.SystemSpaceVO;
import com.fy.pojo.vo.user.UserSpaceVO;
import com.fy.service.SystemService;
import com.fy.utils.RedisUtils;
import com.fy.utils.aliyunUtils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.client.RedisException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.*;

@Slf4j
@Service
public class SystemServiceImpl extends ServiceImpl<SysFunctionMapper, SysFunction> implements SystemService {

    @Autowired
    private ExpansionMapper expansionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private TimeMapper timeMapper;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private SysToolsMapper sysToolsMapper;

    @Autowired
    private SysFunctionMapper sysFunctionMapper;

    /**获取扩容套餐
     *
     * @return
     */
    @Override
    public List<Expansion> getExpansionType() {
        return expansionMapper.selectList(null);
    }

    /**扩容
     *
     * @param nickName
     * @param type
     */
    @Override
    @Transactional(rollbackFor = {SQLException.class})
    public void doExpansion(String nickName, Integer type) {
        Long expansionSpace = expansionMapper.selectById(type).getSpace();
        UserSpaceVO spaceVO = userMapper.selectSpaceByUserName(nickName);
        long useSpace=spaceVO.getUseSpace();
        long totalSpace=spaceVO.getTotalSpace();
        long percentTotalSpace=(totalSpace * 9) / 10;
        if(percentTotalSpace > useSpace){
            throw new ConditionException(MessageConstant.SPACE_FULL);
        }
        userMapper.updateTotalSpaceByName(nickName,expansionSpace+totalSpace);
        String userSpaceKey = nickName + "Space";
        UserSpaceVO NewUserSpaceVO=new UserSpaceVO();
        NewUserSpaceVO.setTotalSpace(expansionSpace+totalSpace);
        NewUserSpaceVO.setUseSpace(useSpace);
        try {
            redisUtils.delete(userSpaceKey);
            redisUtils.setex(userSpaceKey, NewUserSpaceVO, 100);
        } catch (RedisException e) {
            throw new ConditionException(MessageConstant.UNKNOWN_ERROR);
        }

    }

    /**获取登录用户分布统计
     *
     * @return
     */
    @Override
    public List<Position> getRegionalDistribution() {
        return positionMapper.selectList(null);
    }

    /**获取登录时间统计
     *
     * @return
     */
    @Override
    public List<DurationTimeVO> getDurationTime() {
        return timeMapper.getTimeList();
    }

    /**获取系统空间信息
     *
     * @return
     */
    @Override
    public SystemSpaceVO getSystemSpace(HttpSession session) {
        LoginUserVO loginUserVO=(LoginUserVO) session.getAttribute(Constants.SESSION_KEY);
        UserSpaceVO userSpaceVO=userMapper.selectSpaceByUserName(loginUserVO.getNickName());
        SystemSpaceVO spaceVO=new SystemSpaceVO();
        if(loginUserVO.getAdmin()){
            BucketStat bucketStat = aliOssUtil.getBucketStat();
            spaceVO.setOssUseSpace(String.valueOf(bucketStat.getStorageSize()));
            spaceVO.setSystemUseSpace(String.valueOf(userMapper.getTotalUseSpace()));
            spaceVO.setTitle(MessageConstant.ADMIN_OSS_COUNT_TITLE);
        }

        if(!loginUserVO.getAdmin()){
            spaceVO.setOssUseSpace(String.valueOf(userSpaceVO.getTotalSpace()));
            spaceVO.setSystemUseSpace(String.valueOf(userSpaceVO.getUseSpace()));
            spaceVO.setTitle(MessageConstant.USER_SPACE_TITLE);
        }

        return spaceVO;
    }

    /**获取系统工具
     *
     * @return
     */
    @Override
    public List<SysTools> getToolsList() {
        return sysToolsMapper.selectList(null);
    }


    /**获取工具使用统计信息
     *
     * @return
     */
    @Override
    public Map<String, Object> getLast7DaysUsage() {
        List<Map<String, Object>> usageList = sysFunctionMapper.getLast7DaysUsage();

        List<String> systemFunctionList = Arrays.asList(
                "图片上传", "音频上传", "视频上传", "文字识别", "文档上传", "其他上传", "回收站", "分享文件", "你干嘛哎哟"
        );

        Map<String, List<Integer>> dataInfoMap = new HashMap<>();
        for (Map<String, Object> usage : usageList) {
            String date = (String) usage.get("date");
            String title = (String) usage.get("title");
            int count = (int) usage.get("count");

            dataInfoMap.putIfAbsent(date, new ArrayList<>(Collections.nCopies(systemFunctionList.size(), 0)));
            List<Integer> counts = dataInfoMap.get(date);
            counts.set(systemFunctionList.indexOf(title), count);
        }

        List<Map<String, Object>> dataInfoList = new ArrayList<>();
        for (Map.Entry<String, List<Integer>> entry : dataInfoMap.entrySet()) {
            Map<String, Object> dataInfo = new HashMap<>();
            dataInfo.put("text", entry.getKey());
            dataInfo.put("data", entry.getValue());
            dataInfoList.add(dataInfo);
        }

        Map<String, Object> resultData = new HashMap<>();
        resultData.put("systemFunctionList", systemFunctionList);
        resultData.put("dataInfoList", dataInfoList);

        return resultData;
    }
}
